<?php

namespace app\shop\controller\shopper;

use app\Request;
use app\shop\controller\Controller;
use app\common\model\shopper\Shopper as ShopperModel;
use app\common\model\store\Clerk as ClerkModel;
use app\common\model\village\Village;
use app\shop\model\user\User;
class Shopper extends Controller
{
    /**
     * 配送员列表
     * @return \think\response\Json
     */
    public function index()
    {
        $model = new ShopperModel;
        $list = $model->getList($this->postData());
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 小区列表
     * @return \think\response\Json
     */
    public function getVillageList()
    {
        $Village = new Village;
        $list = $Village->getList([],1,2);
        return $this->renderSuccess('', compact('list'));
    }

    /**
     * 添加
     * @return \think\response\Json
     */
    public function add()
    {
        $model = new ShopperModel;
        $Clerk = new ClerkModel;
        $User = new User;
        //Vue要添加的数据
        $data = $this->postData();
        $data['uid'] = intval($data['uid']);

        if(!$User -> where('user_id',$data['uid'])-> where(['is_delete'=>0])-> count()){
            return $this->renderError('该会员不存在');
        }

        if($model -> where('uid',$data['uid'])-> where(['is_delete'=>0]) -> count()){
            return $this->renderError('该会员已经是配送员E1');
        }

        if($model -> where('mobile',$data['mobile'])-> where(['is_delete'=>0]) -> count()){
            return $this->renderError('该手机号码已被占用');
        }

        if($model -> where('mo',$data['uid'])-> where(['is_delete'=>0]) -> count()){
            return $this->renderError('该会员已经是配送员E1');
        }

        if($Clerk -> where('user_id',$data['uid']) -> where(['is_delete'=>0])-> count()){
            return $this->renderError('该会员已经是配送员E2');
        }

        // 新增记录
        if ($model->add($data)) {
            return $this->renderSuccess('添加成功');
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * @param $id
     * @return \think\response\Json
     */
    public function edit($id)
    {
        // 详情
        $model = ShopperModel::detail($id);
        unset($model['password']);
        if ($this->request->isGet()) {
            return $this->renderSuccess('',compact('model'));
        }
        // 修改记录
        if ($model->edit($this->postData())) {
            return $this->renderSuccess('更新成功');
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    /**
     * 删除
     */
    public function delete($id)
    {
        $model = new ShopperModel;
        // 门店详情
        if (!$model->where('id',$id) -> delete()) {
            return $this->renderError('删除失败');
        }
        return $this->renderSuccess($model->getError() ?: '删除成功');

    }


}
